#! /bin/bash
# PHASE1：
# 编译和打包maven工程，在产品目录($PRODUCT_HOME)生成
# 初始化配置文件(*.properties)和可执行文件(*.jar)
# params:
# -skip:  skip maven pack

# PHASE2：
# 将产品目录下全部内容打包成ncc-all.tar
# 放在$PRODUCT_HOME/remote目录下用于远程分发和部署

DEPLOY_HOME=`pwd`
echo scripts home is: $DEPLOY_HOME
NCC_HOME=${DEPLOY_HOME}"/../../"
echo ncc home is: $NCC_HOME
PROXY_HOME=${NCC_HOME}/ncc-component/ncc-proxy
MGR_HOME=${NCC_HOME}/ncc-manager/ncc-clustermgr
REST_HOME=${NCC_HOME}/ncc-manager/ncc-restapi
AGENT_HOME=${NCC_HOME}/ncc-component/ncc-agent
DASH_HOME=${NCC_HOME}/ncc-ui/ncc-dashboard
echo rest home is: $REST_HOME
echo proxy packaged in: $PROXY_HOME/target
echo rest packaged in: $REST_HOME
echo dashboard packaged in: $DASH_HOME
cd $NCC_HOME
if [ "$1" = "skip" ]
then
	echo '[INFO]skip maven package'
else
	mvn clean package -Dmaven.test.skip=true
fi  
#echo executing maven commands in $NCC_HOME
#mvn clean package -Dmaven.test.skip=true 
cd $DEPLOY_HOME
echo executing  commands in $DEPLOY_HOME
PRODUCT_HOME=${DEPLOY_HOME}"/product"
echo cleaning app...
rm -rf $PRODUCT_HOME/*.jar
rm -rf $PRODUCT_HOME/ncc-all.tar
rm -rf $PRODUCT_HOME/*.properties
rm -rf $PRODUCT_HOME/*.sh
rm -rf $PRODUCT_HOME/*.xml
rm -rf $PRODUCT_HOME/agent
rm -rf $PRODUCT_HOME/logs
rm -rf $PRODUCT_HOME/remote
mkdir -p ${PRODUCT_HOME}/agent/main
mkdir -p ${PRODUCT_HOME}/logs
#远程部署文件目录
mkdir -p ${PRODUCT_HOME}/remote
JDK_HOME=${PRODUCT_HOME}/jdk
if [ ! -d $JDK_HOME ]; then  
	echo deploying jdk...
	mkdir -p ${JDK_HOME}
	cd  ${JDK_HOME} 
	tar -xf ${DEPLOY_HOME}/jdk-8u66-linux-x64.tar
else  
	echo 'jdk already exist.'  
fi  
cd $DEPLOY_HOME
echo copying agent to deploy home
cp -R ${AGENT_HOME}/src/main/* $PRODUCT_HOME/agent/main/
echo copying proxy jar to deploy home
cp ${PROXY_HOME}/target/ncc-proxy.jar $PRODUCT_HOME
echo copying rest jar to deploy home
cp ${REST_HOME}/ncc-rest.jar $PRODUCT_HOME
echo copying dashboard jar to deploy home
cp ${DASH_HOME}/ncc-dashboard.jar $PRODUCT_HOME
echo copying CONFIG files to deploy home
cp -R ${MGR_HOME}/src/main/resources/raft.xml $PRODUCT_HOME
cp -R ${REST_HOME}/src/main/resources/*.properties $PRODUCT_HOME
cp -R ${DASH_HOME}/src/main/resources/*.properties $PRODUCT_HOME
#复制配置文件模板
cp -R templates/* $PRODUCT_HOME/remote
#复制命令
cp -R commands/*.sh $PRODUCT_HOME
chmod 755 $PRODUCT_HOME/*.sh
echo 'Packaging for remote deploy...'
cd ${PRODUCT_HOME}
#整体打包，用于远程部署
tar -cf ncc-all.tar .
mv ncc-all.tar ./remote
mv unpack.sh ./remote
mv transfer.sh ./remote
mv init.sh ./remote
echo 'all done!'
echo 'See your product at '[${PRODUCT_HOME}]:
ls ${PRODUCT_HOME}
#echo 'See your product package at' [${PRODUCT_HOME}/remote/ncc-all.tar]
